package com.yc.web;

import com.yc.entity.*;
import com.yc.util.PageUtil;
import com.yc.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class IndexAction {

    @GetMapping("hello")
    public String hello() {
        return "hello world";
    }

    @Resource
    private OrderAction orderAction;
    @Resource
    private UserAction userAction;

    // 默认首页
    @GetMapping({"/","/index.html"})
    public ModelAndView index(ModelAndView mav, @SessionAttribute(required = false) Object loginedUser) {
        // 从order获取分类数据
        Result result = orderAction.queryAll();
        // 将分类添加到数据模型
        mav.addObject("categorys", result.getData());
        //result=userAction.getLoginedUser();
        log.info("loginedUser：{}",loginedUser);
        mav.addObject("loginedUser",loginedUser);

        //查询最新商品
        List<Product> list= orderAction.getnewproduct();
        log.info("list：{}",list);
        mav.addObject("newproduct", list);
        //查询最新商品
        list= orderAction.gethotproduct();
        log.info("list：{}",list);
        mav.addObject("hotproduct", list);

        // 跳转页面(视图)
        mav.setViewName("index");
        return mav;
    }

    @GetMapping("/cart.html")
    public ModelAndView cart(ModelAndView mav, @SessionAttribute(required = false) Object loginedUser){
        //thymeleaf 动态视图 ，页头的分类数据也需要查询
        index(mav,loginedUser);

        Map<String,Object> user=(Map<String,Object>)loginedUser;
        if ( loginedUser==null ){
            mav.setViewName("redirect:/login.html");
            return mav;
        }
        Object uid=user.get("uid");
        int id=Integer.parseInt(uid+"");
        List<Cart> list=orderAction.getCart(id);
        mav.addObject("allcart",list);
        Map<Integer,Product> map=new HashMap();
        double count=0;
        for ( Cart cart: list) {
            Product product=orderAction.getProduct(cart.getPid());
            count+=cart.getCount()*product.getShopPrice();
            map.put(cart.getPid(),product);
        }
        log.info("log：{}",map);
        mav.addObject("allcartmap",map);
        mav.addObject("allcartcount",count);
        mav.setViewName("cart");
        return mav;
    }

    @GetMapping("/clist.html")
    public ModelAndView clistByCsid(ModelAndView mav, @RequestParam(value = "csid",required = false) Integer csid,@RequestParam(value = "cid",required = false) Integer cid,@RequestParam( value = "pageIndex",required = false) Integer pageIndex,@SessionAttribute(required = false) Object loginedUser){
        //thymeleaf 动态视图 ，页头的分类数据也需要查询
        index(mav,loginedUser);
        detils(mav,1,loginedUser);

        if ( pageIndex==null ||pageIndex<=0){
            pageIndex=1;
        }
        mav.addObject("clistMap",null);
        try {
            List<Product> list=new ArrayList<>();
            Map map=new HashMap();
            if ( csid!=null ){
                list=orderAction.getclistByCsid(csid);
                map.put("id",csid);
                map.put("category","csid");
                System.out.println("csid");
            }else if ( cid!=null ){
                list=orderAction.getclistByCid(cid);
                map.put("id",cid);
                map.put("category","cid");
                System.out.println("cid");
            }
            int total=list.size()<=8?1:(list.size()/8+1);
            System.out.println("pageIndex:"+pageIndex);
            PageUtil pageUtil=new PageUtil(pageIndex,8);
            list=pageUtil.get(list);
            mav.addObject("clist",list);
            map.put("curPage",pageIndex);
            map.put("totalPage",total);
            map.put("prePage",pageIndex-1>0?pageIndex-1:null);
            map.put("nextPage",pageIndex+1<=total?pageIndex+1:null);
            mav.addObject("clistMap",map);
            System.out.println(list);
        }catch ( Exception e ){
            e.printStackTrace();
        }
        mav.setViewName("clist");
        return mav;
    }

    @GetMapping("/detils.do")
    public ModelAndView detils(ModelAndView mav,int id,@SessionAttribute(required = false) Object loginedUser) {
        //thymeleaf 动态视图 ，页头的分类数据也需要查询
        index(mav,loginedUser);
        // 从order获取分类数据
        Product product = orderAction.getProduct(id);
        // 将分类添加到数据模型
        mav.addObject("product", product);

        //查询一级分类
        List< Category > list= orderAction.getCategory();
        System.out.println(list);
        mav.addObject("Category", list);
        //查询二级分类
        Map<Integer,List<Categorysecond>> map=new HashMap();
        for ( Category category:list ) {
            List< Categorysecond > m= orderAction.getCategorysecond(category.getCid());
            if ( m==null ){
                continue;
            }
            map.put(category.getCid(),m);
        }
        mav.addObject("Categorysecond", map);

        // 跳转页面(视图)
        mav.setViewName("detail");
        return mav;
    }

    @RequestMapping("login.do")
    public Result login(User user, HttpSession session){
        System.out.println(user);
        Result res=userAction.login(user);
        System.out.println(res);
        if(res.getCode()==1){
            session.setAttribute("loginedUser",res.getData());
            res.setData(null);
        }
        return res;
    }

    @RequestMapping("exit.do")
    public ModelAndView exit(HttpSession session,ModelAndView mav){
        session.setAttribute("loginedUser",null);
        mav.setViewName("index");
        return mav;
    }

    @RequestMapping("addCart.do")
    public ModelAndView addCart( Cart cart, @SessionAttribute Object loginedUser, ModelAndView mav){
        if ( loginedUser==null ){
            mav.setViewName("redirect:/login.html");
            return mav;
        }
        //查询公共数据（页头）
        index(mav,loginedUser);
        Map<String,Object> user=(Map<String,Object>)loginedUser;
        Object uid=user.get("uid");
        cart.setUid(Integer.parseInt(uid+""));
        orderAction.addCart(cart);
        // 查询该用户的所有购物车商品
        cart(mav,loginedUser);
        mav.setViewName("cart");
        return mav;
    }
}
